import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store';
import { initChat, initNotify } from '../helper/socket';
import Signup from '../views/Signup.vue';
import Signin from '../views/Signin.vue';
import Home from '../views/Home/index.vue';
import Info from '../views/Info/index.vue';
import Chat from '../views/Chat/index.vue';
import ChatBox from '../views/ChatBox/index.vue';
import VueStudy from '../views/VueStudy/index.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Home',
    components: {
      default: Home,
      chatBox: ChatBox,
    },
  },
  {
    path: '/info',
    name: 'Info',
    components: {
      default: Info,
      chatBox: ChatBox,
    },
  },
  {
    path: '/chat',
    name: 'Chat',
    components: {
      default: Chat,
      chatBox: ChatBox,
    },
  },
  {
    path: '/signup',
    name: 'Signup',
    component: Signup,
  },
  {
    path: '/signin',
    name: 'Signin',
    component: Signin,
  },
  {
    path: '/vuestudy',
    name: 'VueStudy',
    component: VueStudy,
  },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

const whiteList = ['Signup', 'Signin'];

router.beforeEach((to, from, next) => {
  if (whiteList.some((name) => name === to.name)) {
    next();
    return;
  }

  const token = localStorage.getItem('__token__');

  if (token) {
    Promise.all([initChat(store), initNotify(store)]).then(() => {
      next();
    });

    return;
  }

  next('/signin');
});

export default router;
